﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Server.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class UpdateProject : IService
    {
        /// <summary>
        /// 요청받은 메시지의 본문
        /// </summary>
        CCL.SocketMessage.Request.UpdateProject m_body;

        /// <summary>
        /// 새로운 서비스를 생성합니다.
        /// </summary>
        /// <param name="body">요청받은 메시지 본문</param>
        public UpdateProject(CCL.SocketMessage.Request.UpdateProject body)
        {
            m_body = body;
        }

        /// <summary>
        /// 서비스를 시작합니다.
        /// </summary>
        /// <returns>전송할 byte배열</returns>
        public byte[] Execute()
        {
            byte[] returnBytes = null;

            int poolId = Network.FDQManager.Allocate();
            int fileCount = 0;

            Network.FDQManager.FDQ ftq = Network.FDQManager.GetFDQ(poolId);

            using (SqlConnection sqlCon = new SqlConnection(Properties.Resources.ConnectionString))
            {
                sqlCon.Open();
                try
                {
                    SqlCommand sqlCmd = new SqlCommand(@"
                        SELECT [path], max(revision) AS [maxRevision]
                        FROM [ProjectFile]
                        WHERE [projectId] = @projectId
                        AND	[deletion] = 0
                        GROUP BY [path]
                        HAVING max(revision) > @crev
                    ", sqlCon);

                    sqlCmd.Parameters.AddWithValue("@projectId", m_body.ProjectID);
                    sqlCmd.Parameters.AddWithValue("@crev", m_body.CurrentRevision);

                    SqlDataAdapter dAdapter = new SqlDataAdapter();
                    dAdapter.SelectCommand = sqlCmd;

                    DataSet ds = new DataSet();
                    dAdapter.Fill(ds);

                    fileCount = ds.Tables[0].Rows.Count;

                    foreach (DataRow dRow in ds.Tables[0].Rows)
                    {
                        string path = (string)dRow["path"];
                        int revision = (int)dRow["maxRevision"];

                        string realPath = m_body.ProjectID + "\\" + revision + "\\" + path;

                        ftq.PushFilePath(new Network.ManagedFile(realPath, revision));
                    }

                    ds.Dispose();

                    // 성공 메시지 빌드
                    CCL.SocketMessage.Response.FileDownloadReady rft = new CCL.SocketMessage.Response.FileDownloadReady(poolId, fileCount);
                    CCL.SocketMessage.Message msg = CCL.SocketMessage.Message.MessageResponseBuilder(rft);

                    returnBytes = msg.GetByte();
                }
                catch (System.Exception ex)
                {
                    // 실패 메시지 빌드
                    CCL.SocketMessage.Response.FileDownloadReady rft = new CCL.SocketMessage.Response.FileDownloadReady(ex.Message);
                    CCL.SocketMessage.Message msg = CCL.SocketMessage.Message.MessageResponseBuilder(rft);

                    returnBytes = msg.GetByte();
                }
                finally
                {
                    sqlCon.Close();
                }
            }

            return returnBytes;
        }
    }
}
